package com.example.easytts.service

import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.http.MediaType
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import com.fasterxml.jackson.annotation.JsonIgnoreProperties

@Service
class DeepSeekService(
    @Value("\${deepseek.api.key}")
    private val apiKey: String,
    @Value("\${deepseek.api.url:https://api.deepseek.com/v1/chat/completions}")
    private val apiUrl: String
) {
    private val webClient = WebClient.builder()
        .defaultHeader("Authorization", "Bearer $apiKey")
        .defaultHeader("Content-Type", "application/json")
        .build()

    private val objectMapper = jacksonObjectMapper()

    data class DeepSeekRequest(
        val model: String = "deepseek-chat",
        val messages: List<Message>,
        val temperature: Double = 0.7,
        val max_tokens: Int = 2048
    )

    data class Message(
        val role: String,
        val content: String
    )

    @JsonIgnoreProperties(ignoreUnknown = true)
    data class DeepSeekResponse(
        val id: String,
        val choices: List<Choice>,
        val usage: Usage
    )

    @JsonIgnoreProperties(ignoreUnknown = true)
    data class Choice(
        val index: Int,
        val message: Message,
        val finish_reason: String
    )

    @JsonIgnoreProperties(ignoreUnknown = true)
    data class Usage(
        val prompt_tokens: Int,
        val completion_tokens: Int,
        val total_tokens: Int
    )

    fun generateText(prompt: String, model: String = "deepseek-chat", temperature: Double = 0.7): String {
        val request = DeepSeekRequest(
            model = model,
            messages = listOf(Message("user", prompt)),
            temperature = temperature
        )

        val response = webClient.post()
            .uri(apiUrl)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(request)
            .retrieve()
            .bodyToMono(String::class.java)
            .block() ?: throw RuntimeException("Failed to generate text via DeepSeek API")

        val responseObj = objectMapper.readValue<DeepSeekResponse>(response)
        return responseObj.choices.firstOrNull()?.message?.content 
            ?: throw RuntimeException("No response content from DeepSeek API")
    }
} 